package com.carambatv.android.ui;

import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.carambatv.android.R;
import com.carambatv.android.adapter.GridAdapter;
import com.carambatv.android.db.ChannelQuery;
import com.carambatv.android.db.VideoQuery;
import com.carambatv.android.model.ChannelObject;
import com.carambatv.android.service.UpdateChannelService;
import com.carambatv.android.utils.Config;
import com.carambatv.android.utils.DetachableResultReceiver;
import com.carambatv.android.utils.DetachableResultReceiver.Receiver;
import com.carambatv.android.utils.NotifyingAsyncQueryHandler;

public class GrigFragment extends Fragment implements OnItemClickListener, Receiver, NotifyingAsyncQueryHandler.AsyncQueryListener {

	private GridView mGrid;
	private GridAdapter gridAdapter;
	private DetachableResultReceiver receiver;
	private NotifyingAsyncQueryHandler mHandler;
	private Cursor mCursor;
	int mStackLevel = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			mStackLevel = savedInstanceState.getInt("level");
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("level", mStackLevel);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this);
		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);

		mHandler.cancelOperation(ChannelQuery._TOKEN);
		mHandler.startQuery(ChannelQuery._TOKEN, null, ChannelObject.CONTENT_URI, ChannelQuery.PROJECTION, null, null, ChannelObject.SUBSCRIBERS_SORT);

		for (int i = 0; i < Config.arrayChannels.length; i++) {
			Intent upfateIntent = new Intent(Intent.ACTION_SYNC, null, getActivity(), UpdateChannelService.class);
			upfateIntent.putExtra(UpdateChannelService.EXTRA_STATUS_RECEIVER, receiver);
			upfateIntent.putExtra(UpdateChannelService.EXTRA_REQUEST_CODE, Config.YTUBE);
			upfateIntent.putExtra(Config.TYPE, Config.arrayChannels[i]);
			getActivity().startService(upfateIntent);
		}

		Configuration config = getResources().getConfiguration();
		setColumnNumber(config);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.home, null);
		mGrid = (GridView) view.findViewById(R.id.grid_layout);
		mGrid.setOnItemClickListener(this);
		return view;
	}

	@Override
	public void onResume() {
		if (mCursor != null) {
			mCursor.requery();
		}
		super.onResume();
	}

	private void setColumnNumber(Configuration newConfig) {
		switch (newConfig.orientation) {
		case Configuration.ORIENTATION_LANDSCAPE:
			mGrid.setNumColumns(3);
			break;
		case Configuration.ORIENTATION_PORTRAIT:
			mGrid.setNumColumns(2);
			break;
		default:
			break;
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		setColumnNumber(newConfig);
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		String type = null;
		String title = null;

		if (mCursor.moveToPosition(position)) {
			type = mCursor.getString(VideoQuery.TYPE);
			title = mCursor.getString(VideoQuery.TITLE);
		}
		mStackLevel++;
		// Instantiate a new fragment.
		Fragment newFragment = FragmentVideos.newInstance(mStackLevel, type, title);
		// Add the fragment to the activity, pushing this transaction
		// on to the back stack.
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		ft.replace(R.id.grid_fragment, newFragment);
		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		ft.addToBackStack(null);
		ft.commit();

	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateChannelService.STATUS_RUNNING:
			break;
		case UpdateChannelService.STATUS_ERROR:
			break;
		case UpdateChannelService.STATUS_FINISHED:
			if (mCursor != null) {
				mCursor.requery();
			}
		}
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case ChannelQuery._TOKEN:

			if (cursor != null) {
				if (mCursor != null) {
					getActivity().stopManagingCursor(mCursor);
					mCursor = null;
				}
				mCursor = cursor;
				getActivity().startManagingCursor(mCursor);
				if (gridAdapter == null) {
					gridAdapter = new GridAdapter(getActivity(), mCursor);
					mGrid.setAdapter(gridAdapter);
				} else {
					gridAdapter.changeCursor(mCursor);
					gridAdapter.notifyDataSetChanged();
				}
			}
			break;
		default:
			break;
		}

	}
}
